package ws.jdbc.concurrent.driver.sqlserver.tds.datatypes;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 *
 * @author Wilson Santos, 36228 <wilson.santos@ua.pt>
 */
public abstract class TYPE_VARLEN {

  protected int length;
  protected final int size;

  public TYPE_VARLEN(int length, int size) {
    this.length = length;
    this.size = size;
  }

  public static TYPE_VARLEN create(byte varlentype, int length) {
    TYPE_VARLEN ret = null;
    switch (varlentype) {
      case VARLENTYPE.INTTYPE:
      case VARLENTYPE.FLTNTYPE:
      case VARLENTYPE.DATETIMNTYPE:
        ret = new BYTELEN(length);
        break;
      case VARLENTYPE.BIGVARBINTYPE:
      case VARLENTYPE.BIGVARCHRTYPE:
      case VARLENTYPE.NVARCHARTYPE:
        ret = new USHORTCHARBINLEN(length);
        break;
      default:
        throw new IllegalArgumentException("Error: unknown varlentype (0x" + varlentype + ")");
    }
    return ret;
  }

  public static TYPE_VARLEN read(final ByteBuffer stream, byte varlentype) throws IOException {
    return create(varlentype, 0).read(stream);
  }

  public int getLength() {
    return length;
  }

  public abstract byte[] getBytes();

  public abstract int size();

  public abstract TYPE_VARLEN read(final ByteBuffer stream) throws IOException;

  public abstract boolean wasNull();

  @Override
  public String toString() {
    return "" + length;
  }
}
